import styles from './glass.module.less'
import { imgConfig } from './config'
import { useRef, useState } from 'react'

export default function Glass() {
  // 存储选中的图片
  const [img, setImg] = useState<string>('')
  // 遮罩
  const [bar, setBar] = useState('')
  // 放大图片
  const [magShowIng, setMagShowIng] = useState('')
  //
  const magIng = useRef<HTMLElement>(document.getElementById('ma')!)
  const glass = useRef<HTMLElement>(document.getElementById('glass')!)

  const imgClick = (img: string) => {
    setImg(img)
  }
  // 获取对应放大背景图的宽高
  const getImgBackgroundSize = (ele: any) => {
    const obj: { width: number; height: number } = {
      width: 0,
      height: 0,
    }

    // 自定义函数

    // h获取对象的背景图宽高
    const w = window.getComputedStyle(ele).backgroundSize
    // 返回一维数组
    const sizeArr = w.split(' ')
    if (sizeArr.length === 1) {
      obj.width = parseInt(sizeArr[0])
      obj.height = parseInt(sizeArr[0])
    } else {
      obj.width = parseInt(sizeArr[0])
      obj.height = parseInt(sizeArr[1])
    }
    return obj
  }

  // 事件
  const onMouseEnter = (e: any) => {
    setBar('bar')
    setMagShowIng('magShowIng')
  }
  const onMouseMove = (e: any) => {
    const Bar: HTMLElement = document.querySelector('#bar') as HTMLElement
    // 获取最新的样式
    const mapIng: any = magIng.current
    const MapIngoffsetLeft = mapIng.offsetLeft
    const MapIngoffsetTop = mapIng.offsetTop
    // 遮罩层的位置
    let x = e.pageX - MapIngoffsetLeft - Bar.offsetWidth / 2 - 250
    let y = e.pageY - MapIngoffsetTop - Bar.offsetHeight / 2 - 125

    if (x < 0) {
      x = 0
    }
    if (x > mapIng.clientWidth - Bar.offsetWidth - 0) {
      x = mapIng.clientWidth - Bar.offsetWidth - 0
    }
    if (y < 0) {
      y = 0
    }
    if (y > mapIng.clientHeight - Bar.offsetHeight - 0) {
      y = mapIng.clientHeight - Bar.offsetHeight - 0
    }
    Bar.style.left = x + 'px'
    Bar.style.top = y + 'px'
    // 背景图片的定位 = 背景图片的宽/高 * 遮盖层的定位 /  显示区域的宽/高

    let glassX = (getImgBackgroundSize(glass.current).width * x) / magIng.current.clientWidth
    let glassY = (getImgBackgroundSize(glass.current).height * y) / magIng.current.clientHeight

    glass.current.style.backgroundPosition = `-${glassX}px -${glassY}px`
  }
  const onMouseLeave = (e: any) => {
    setBar('')
    setMagShowIng('')
  }

  return (
    <div id={styles.glass}>
      {imgConfig.map((item, key) => {
        return <img key={key} src={item.small} className='imgUrl' alt='侯德康' onClick={() => imgClick(item.big)} />
      })}
      <div className={'mag'}>
        {/* @ts-ignore */}
        <div id='ma' className={'magIng'} onMouseEnter={onMouseEnter} onMouseMove={onMouseMove} onMouseLeave={onMouseLeave} ref={magIng}>
          <img src={img} alt='请选择一张图片' />
          <div className={bar} id='bar'></div>
        </div>
        {/* @ts-ignore */}
        <div className={magShowIng} style={{ backgroundImage: `url(${img})` }} ref={glass}></div>
      </div>
    </div>
  )
}
